/**
 * Api 请求常用方法封装
 */
import {
	Ajax
} from './ajax'
import * as SSKEYS from './session-storage-keys'
import {
	getToken
} from '@/common/auth'
import store from '@/store'

/**
 * API请求相关操作
 */
export class ApiObject {
	constructor(host, module = null) {
		this._host = host
		this._module = module
	}

	module(module) {
		return new ApiObject(this._host, module)
	}

	/**
	 * API 请求
	 * @param method 请求方式
	 * @param name  方法名称
	 * @param data  请求参数
	 * @param gac 验证码
	 * @param timeout
	 * @param defaultError 处理默认错误
	 * @param module
	 * @returns {Promise<>}
	 */
	api({
		method,
		name,
		data,
		gac,
		timeout,
		defaultError = false,
		module,
		responseType = null,
		isToken = true
	} = {}) {
		// debugger
		const headers = {}
		const token = getToken()
		if (token && isToken) {
			headers['Authorization'] = 'Bearer ' + token
		}
		if (timeout) {
			headers['timeout'] = timeout
		}
		let url = this._host + name
		module = module || this._module
		if (module) {
			url = `/${module}`
		}

		const ajax = Ajax.ajax({
			method,
			url,
			timeout,
			params: data,
			headers,
			responseType
		})
		return ajax
	}

	get(name, params, {
		gac,
		timeout,
		isToken = true,
		responseType = null,
		defaultError = true,
		module,
	} = {}) {
		return this.api({
			method: 'GET',
			name,
			data: params,
			gac,
			timeout,
			isToken,
			defaultError,
			module,
			responseType
		})
	}

	post(name, params, {
		gac,
		timeout,
		isToken = true,
		responseType = null,
		defaultError = true,
		module,
	} = {}) {

		return this.api({
			method: 'POST',
			name,
			data: params,
			gac,
			timeout,
			isToken,
			defaultError,
			module,
			responseType
		})
	}

	put(name, params, {
		gac,
		timeout,
		isToken = true,
		responseType = null,
		defaultError = true,
		module
	} = {}) {
		return this.api({
			method: 'PUT',
			name,
			data: params,
			gac,
			isToken,
			timeout,
			defaultError,
			module,
			responseType
		})
	}

	patch(name, params, {
		gac,
		timeout,
		isToken = true,
		responseType = null,
		defaultError = true,
		module
	} = {}) {
		return this.api({
			method: 'PATCH',
			name,
			data: params,
			gac,
			timeout,
			isToken,
			defaultError,
			module,
			responseType
		})
	}

	delete(name, params, {
		gac,
		timeout,
		isToken = true,
		responseType = null,
		defaultError = true,
		module
	} = {}) {
		return this.api({
			method: 'DELETE',
			name,
			data: params,
			gac,
			isToken,
			timeout,
			defaultError,
			module,
			responseType
		})
	}
}

const Api = new ApiObject(``)

export {
	Api
}
